package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.Cardtype;
import com.qianniu.napi.admin.service.ICardService;
import com.qianniu.napi.admin.service.IMerchantAppService;
import com.qianniu.napi.admin.service.IMerchantService;
import com.qianniu.napi.admin.service.IRedisService;
import com.qianniu.napi.common.util.DateUtil;
import com.qianniu.napi.common.util.ExportExcel;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.ReadExcel;
import org.apache.http.HttpResponse;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.lang.reflect.Executable;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * <p>
 * </p>
 *
 * @author chenxuebin
 * @since 2018-12-18
 */
@Controller
public class CardController {

    private static final Logger logger = LoggerFactory.getLogger(CardController.class);

    @Autowired
    private ICardService cardService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IMerchantAppService merchantappService;

    @RequestMapping("admin/card/index")
    public String index(Model model) {
        User bean = (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("utype", bean.getUserType());

        if (ObjectUtil.getUserType() == 99) {
            List<MerchantApp> mapps = merchantappService.selectList(new EntityWrapper<MerchantApp>().setSqlSelect("id,name").eq("version_type",4));
            model.addAttribute("mapps", mapps);
        }

        return "admin/card";
    }

    @RequestMapping("/admin/card/list")
    @ResponseBody
    public Page<Card> list(@RequestParam(value = "offset", required = false) Integer offset,
                           @RequestParam(value = "status", required = false) Integer status,
                           @RequestParam(value = "search", required = false) String search,
                           @RequestParam(value = "limit", required = false) Integer limit) {
        Wrapper<Card> wrapper = new EntityWrapper<Card>();
        if(ObjectUtil.getIsAdmin()!=1)
        wrapper.eq("mid", ObjectUtil.getMid());

        wrapper.orderBy("id", false);
        Page<Card> page = cardService.selectPage(new Page<Card>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/card/add")
    public String add(@Valid Card bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        return "admin/card";
    }

    @RequestMapping("/admin/card/kaika")
    public String kaika(Integer num, Integer expire,Long targetmpid,
                      HttpServletResponse res, Model model) {
        logger.debug("=====================kaika");
        logger.debug("=====================num="+num);
        logger.debug("=====================expire="+expire);
        if(num==null||num<1){
            model.addAttribute("msg", "开卡张数有误");
            return "admin/lipin";
        }
        if(expire==null||expire<0){
            model.addAttribute("msg", "有效期参数有误");
            return "admin/lipin";
        }
        Card card = cardService.selectOne(new EntityWrapper<Card>()
                .setSqlSelect("max(cardno) cardno")
                .where(" cardno like '110%' "));

        if(card==null){
            model.addAttribute("msg", "请初始化卡信息");
            return "admin/lipin";
        }

        MerchantApp mapp = redisService.getMApp(targetmpid);
        Long initno = Long.valueOf(card.getCardno());
        List<Card> list = new ArrayList<Card>();
        Date now = new Date();
        for(int i=0;i<num;i++){
            initno++;
            Card c = new Card();
            c.setCardno(initno.toString());
            c.setPwd(ObjectUtil.randomNum(6));
            c.setCardtype(Cardtype.jifen.getVal());
            c.setTypename("积分卡");
            c.setAmount(new BigDecimal(100));
            c.setExpire(expire);
            c.setIsOutdate(-1);
            c.setMid(mapp.getMid());
            c.setMpid(mapp.getId());
            c.setCreatetime(now);

            c.setIsOutdate(-1);
            c.setSxtype(1);// 绑定生效
            c.setState(-1);// 绑定生效
            list.add(c);
            c.insert();
        }

        try {
            ExportExcel ee = new ExportExcel("", Card.class);
            ee.setDataList(list);
            ee.write(res, DateUtil.getShortToday() + "积分卡号卡密.xlsx");
        }catch (Exception e){
            logger.error("",e);
        }

        return null;
    }

    @RequestMapping("/admin/card/import")
    @ResponseBody
    public Card impexcel(long id) {
        Card card = cardService.selectById(id);
        return card;
    }


    @RequestMapping("/admin/card/getCardById")
    @ResponseBody
    public Card getCardById(long id) {
        Card card = cardService.selectById(id);
        return card;
    }

    @RequestMapping("/admin/card/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = cardService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/card/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Card bean = new Card();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        cardService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/card/modify")
    public String update(Card bean) {
        bean.setModifytime(new Date());
        boolean isSuccc = cardService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping(value = "/admin/upload/dhkexcel", method = RequestMethod.GET)
    @ResponseBody
    public JsonDO dhkexcel(@RequestParam(value = "type", required = true) Integer type,
                           @RequestParam(value = "targetmid", required = true) Long targetmid,
                           @RequestParam(value = "targetmpid", required = true) Long targetmpid,
                           String path) {

        JsonDO json = new JsonDO();

        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String, String>> list = null;
        String cellData = null;
        Card card = null;

        wb = ReadExcel.readExcel(path);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<Map<String, String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(0);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = row.getPhysicalNumberOfCells();
            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();

                card = new Card();
                card.setCardtype(type);
                card.setAmount(new BigDecimal(100));

                card.setIsOutdate(-1);
                card.setSxtype(1);
                card.setExpire(365);
                card.setState(1);
                card.setIsUsed(-1);
                card.setCreatetime(new Date());
                card.setMid(targetmid);
                card.setMpid(targetmpid);
                row = sheet.getRow(i);
                if (row != null) {
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String) ReadExcel.getCellFormatValue(row.getCell(j));
                        if(j==0)card.setCardno(cellData);
                        if(j==1)card.setPwd(cellData);
                    }
                    card.insert();
                } else {
                    break;
                }
                list.add(map);
            }
        }

        return json;
    }
}
